package com.ilop.sthome.mvp.present.message;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.util.Patterns;

import com.alibaba.fastjson.JSON;
import com.aliyun.iot.aep.sdk.apiclient.callback.IoTResponse;
import com.example.common.base.OnCallBackToEdit;
import com.example.common.base.OnCallBackToRefresh;
import com.example.common.mvp.BasePresenterImpl;
import com.ilop.sthome.data.greenDao.DeviceShareBean;
import com.ilop.sthome.mvp.contract.message.ShareContract;
import com.ilop.sthome.mvp.model.ShareModel;
import com.ilop.sthome.mvp.model.common.ShareModelImpl;
import com.example.common.mvp.onModelCallBack;
import com.ilop.sthome.ui.dialog.BaseDialog;
import com.ilop.sthome.ui.dialog.SharerDialog;
import com.siterwell.familywellplus.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * @author skygge
 * @Date on 2020-02-19.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class SharePresenter extends BasePresenterImpl<ShareContract.IView> implements ShareContract.IPresent {

    private Context mContext;
    private ShareModelImpl mModel;
    private Handler mHandler;
    private List<DeviceShareBean> mShareList;

    public SharePresenter(Context mContext) {
        this.mContext = mContext;
        mHandler = new Handler();
        mModel = new ShareModel(mHandler);
    }

    @Override
    public void getShareNoticeList() {
        mModel.getShareNoticeList(1, 50, new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {
                if (response.getCode() == 200){
                    Object data = response.getData();
                    try {
                        JSONObject jsonObject = (JSONObject) data;
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        mShareList= JSON.parseArray(jsonArray.toString(), DeviceShareBean.class);
                        getSharerList(mShareList);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }else {
                    mHandler.post(()-> mView.dismissProgress());
                }
            }

            @Override
            public void onFailure(Exception e) {
            }
        });
    }

    @Override
    public void getSharerList(List<DeviceShareBean> mList) {
        if (mList != null && mList.size()>0){
            mHandler.post(()->mView.showShareList(mList));
        }else {
            mHandler.post(()->mView.showNoSharer());
        }
        mHandler.post(()-> mView.dismissProgress());
    }

    @Override
    public void addSharer(String iotId) {
        SharerDialog mDialog = new SharerDialog(mContext, new OnCallBackToEdit() {
            @Override
            public void onConfirm(String name) {
                shareDevicesAndScenes(iotId, name, checkAccountNumber(name));
            }

            @Override
            public void onCancel() {

            }
        });
        mDialog.setTitle(mContext.getString(R.string.add_sharer));
        mDialog.setMsg(mContext.getString(R.string.after_add_sharer));
        mDialog.setEditHint(mContext.getString(R.string.phone_hint) + "/" + mContext.getString(R.string.person_email));
        mDialog.show();
    }

    @Override
    public void shareDevicesAndScenes(String iotId, String account, String type) {
        mModel.shareDevicesAndScenes(iotId, account, type, new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {
                if (response.getCode() == 200){
                    getShareNoticeList();
                    mHandler.post(()-> mView.showToastMsg(mContext.getString(R.string.ali_share_list) + mContext.getString(R.string.success)));
                }else {
                    mHandler.post(()-> mView.showToastMsg(mContext.getString(R.string.ali_share_list) + mContext.getString(R.string.failed)));
                }
            }

            @Override
            public void onFailure(Exception e) {
            }
        });
    }

    @Override
    public void cancelShare(String recordId) {
        BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                mModel.cancelShare(recordId, new onModelCallBack() {
                    @Override
                    public void onResponse(IoTResponse response) {
                        if (response.getCode() == 200){
                            mHandler.post(()-> {
                                getShareNoticeList();
                                mView.showToastMsg(mContext.getString(R.string.cancel_success));
                            });
                        }else {
                            mHandler.post(()-> mView.showToastMsg(response.getLocalizedMsg()));
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                    }
                });
            }

            @Override
            public void onCancel() {

            }
        });
        mDialog.setMsg(mContext.getString(R.string.delete_sharer));
        mDialog.show();
    }

    @Override
    public void confirmShare(String recordId) {
        BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                mModel.confirmShare(recordId, 1, new onModelCallBack() {
                    @Override
                    public void onResponse(IoTResponse response) {
                        if (response.getCode() == 200){
                            mHandler.post(SharePresenter.this::getShareNoticeList);
                        }else {
                            mHandler.post(()-> mView.showToastMsg(response.getLocalizedMsg()));
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                    }
                });
            }

            @Override
            public void onCancel() {
                mModel.confirmShare(recordId, 0, new onModelCallBack() {
                    @Override
                    public void onResponse(IoTResponse response) {
                        if (response.getCode() == 200){
                            mHandler.post(SharePresenter.this::getShareNoticeList);
                        }else {
                            mHandler.post(()-> mView.showToastMsg(response.getLocalizedMsg()));
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                    }
                });
            }
        });
        mDialog.setTitleAndButton(mContext.getString(R.string.agree_share), mContext.getString(R.string.disagree), mContext.getString(R.string.agree));
        mDialog.show();
    }

    @Override
    public void onConfirmUnbind(String iotId, String id) {
        BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                mModel.getBindingByDevice(iotId, 1, 10, 0, new onModelCallBack() {
                    @Override
                    public void onResponse(IoTResponse response) {
                        if (response.getCode() == 200){
                            try {
                                Object data = response.getData();
                                JSONObject jsonObject = (JSONObject) data;
                                JSONArray jsonArray = jsonObject.getJSONArray("data");
                                if (jsonArray.isNull(0)){
                                    String tip = String.format(mContext.getString(R.string.has_been_unbind_with_an), id);
                                    mHandler.post(()-> mView.showToastMsg(tip));
                                    return;
                                }
                                String list1 = jsonArray.getString(0);
                                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(list1);
                                String identityId = jsonObject1.getString("identityId");
                                Log.i("AAA", "onResponse: " + identityId);
                                unbindByManager(identityId, iotId);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else {
                            mHandler.post(()-> mView.showToastMsg(response.getLocalizedMsg()));
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                    }
                });
            }

            @Override
            public void onCancel() {

            }
        });
        mDialog.setMsg(mContext.getString(R.string.delete_sharer));
        mDialog.show();
    }

    private void unbindByManager(String identityId, String iotId){
        mModel.unbindByManager(identityId, iotId, new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {
                if (response.getCode() == 200){
                    getShareNoticeList();
                    mHandler.post(()-> mView.showToastMsg(mContext.getString(R.string.cancel_success)));
                }else {
                    mHandler.post(()-> mView.showToastMsg(response.getLocalizedMsg()));
                }
            }

            @Override
            public void onFailure(Exception e) {
                mHandler.post(()-> mView.showToastMsg(mContext.getString(R.string.failed)));
            }
        });
    }

    @Override
    public void clearShareNoticeList() {
        if (mShareList != null && mShareList.size()>0){
            showClearDialog();
        }else {
            showEmptyDialog(mContext.getString(R.string.no_message));
        }
    }

    private void showClearDialog(){
        BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                mModel.clearShareNoticeList(new onModelCallBack() {
                    @Override
                    public void onResponse(IoTResponse response) {
                        if (response.getCode() == 200){
                            mHandler.post(()-> {
                                getShareNoticeList();
                                mView.showToastMsg(mContext.getString(R.string.success));
                            });
                        }else {
                            mHandler.post(()-> mView.showToastMsg(response.getLocalizedMsg()));
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        mHandler.post(()-> mView.showToastMsg(mContext.getString(R.string.failed)));
                    }
                });
            }

            @Override
            public void onCancel() {

            }
        });
        mDialog.setMsg(mContext.getString(R.string.clear_all_share));
        mDialog.show();
    }

    private void showEmptyDialog(String title){
        BaseDialog mDialog = new BaseDialog(mContext);
        mDialog.setCancelVisibility(true);
        mDialog.setMsg(title);
        mDialog.setCancelText(mContext.getString(R.string.initialzation_guidance_button));
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.show();
    }

    private String checkAccountNumber(String name) {
        if (Patterns.EMAIL_ADDRESS.matcher(name).matches()){
            return "EMAIL";
        }else if (Patterns.PHONE.matcher(name).matches()){
            return "MOBILE";
        }else {
            return null;
        }
    }
}
